package com.ogawa.a7517.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import com.ogawa.a7517.R;
import com.ogawa.a7517.utils.ViewUtil;


/**
 * Created by wuyr on 18-5-22 下午10:32.
 */
public class HalfCircleView extends View {

    public HalfCircleView(Context context) {
        super(context);
    }

    public HalfCircleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public HalfCircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(mBitmap, 0, 0, null);
    }

    private Path mPath = new Path();
    private Paint mPaint = new Paint();
    private Bitmap mBitmap;
    private Canvas mCanvas;

    {
        mPaint.setAntiAlias(true);
        mPaint.setColor(getContext().getResources().getColor(R.color.color1151));
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(10);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
        mCanvas = new Canvas(mBitmap);
        initPath();
    }

    private void initPath() {
        float top = ViewUtil.dip2px(102, getContext());
        float bottom = ViewUtil.dip2px(508, getContext());
        float offset = (bottom - top) / 2f;
        float left = mBitmap.getWidth() - ViewUtil.dip2px(57, getContext()) - offset;
        float right = mBitmap.getWidth() - ViewUtil.dip2px(57, getContext()) + offset;
        mPath.moveTo(mBitmap.getWidth(), top);
        mPath.lineTo(mBitmap.getWidth() - ViewUtil.dip2px(57, getContext()), top);
        RectF rectF = new RectF(left, top, right, bottom);
        mPath.addArc(rectF, -90, -180);
        mPath.lineTo(mBitmap.getWidth(), bottom);
        setPath(mPath);
    }

    public Path getPath() {
        return mPath;
    }

    public void clear() {
        setPath(new Path());
    }

    public void setPath(Path path) {
        mPath = path;
        mBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_4444);
        mCanvas = new Canvas(mBitmap);
        mCanvas.drawPath(mPath, mPaint);
        invalidate();
    }

}
